﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using QuDao;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using FineUICore;
using Kalman;
using System.Xml.Schema;

namespace AdminUI.Pages
{
    public partial class LoginModel : BaseModel
    {
        public string Window1Title { get; set; }

        public void OnGet()
        {
            ViewBag.Title = "渠道通 - 管理中心";
            LoadData();
        }

        private void LoadData()
        {
            //Window1Title = String.Format("AdminUI v{0}", GetProductVersion());
            Window1Title = "渠道通 - 用户登录";

        }

        public async Task<IActionResult> OnPostBtnSubmit_ClickAsync(string tbxUserName, string tbxPassword)
        {
            var userName = tbxUserName.Trim();
            var password = tbxPassword.Trim();

            try
            {
                var user = SysUserBO.Instance.CheckLogin(userName, password);
                await LoginSuccess(user);// 登录成功

                ActionLogBO.Instance.Add(new ActionLogAddDto
                {
                    TID = user.TID,
                    UserID = user.UserID,
                    UserName = user.UserName,
                    TrueName = user.TrueName,
                    ActionType = ActionType.登录.ToString(),
                    ClientIP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(),
                    ModuleUrl = Request.Path.ToString(),
                    Memo = $"用户已登录{user.LoginCount}次"
                });

                return RedirectToPage("/Index"); // 重定向到登陆后首页
            }
            catch (AppException ex)
            {
                Alert.Show(ex.Message);
            }

            return UIHelper.Result();
        }

        private async Task LoginSuccess(SysUser user)
        {
            var roleID = user.RoleID.ToString();//多角色ID用逗号分隔（默认为单角色模式，可以扩展为多角色模式）
            var tenant = TenantBO.Instance.GetItem(user.TID);
            var claims = new[]
            {
                new Claim("UserID", user.UserID.ToString()),
                new Claim("UserName", user.UserName),
                new Claim("TrueName", user.TrueName),
                new Claim("UserType", user.UserType.ToString()),
                new Claim("TID", user.TID.ToString()),
                new Claim("TenantName", tenant == null ? string.Empty : tenant.TenantName),
                new Claim("MAName", tenant == null ? string.Empty : tenant.MAName),
                new Claim("MBName", tenant == null ? string.Empty : tenant.MBName),
                new Claim("MCName", tenant == null ? string.Empty : tenant.MCName),
                new Claim("RoleID", roleID)
             };

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var userInfo = new ClaimsPrincipal(claimsIdentity);
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                userInfo,
                new AuthenticationProperties()
                {
                    IsPersistent = false
                });

        }
    }
}
